package com.dushibao.web.editor;

import com.alibaba.fastjson.JSON;
import com.dushibao.util.EditorResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@WebServlet("/editor/upload")
@MultipartConfig(location = "c:/aServer/upload",maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*5,fileSizeThreshold = 10)
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");//可以获得请求参数

        Collection<Part> parts = req.getParts();
        List<String> urls = new ArrayList<>();

        if(parts!=null){
            for (Part part : parts) {
                if(part.getSubmittedFileName()==null){
                    break;
                }
                //提交的文件名 我们上传后在服务器上面 也保存为这个文件名
                //当然如果文件太多 可以使用UUID作为文件名
                String fileName = part.getSubmittedFileName();

                //String toPath = "c:/b2b2c/aFile/"+fileName;

                urls.add("http://localhost:8001/upload/"+fileName);

                part.write(fileName);
            }
        }
        String ret = JSON.toJSONString(EditorResult.success(urls));
        System.out.println(ret);
        resp.getWriter().write(ret);
    }
}
